<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Exemple de liste triable par glisser/déposer</title>
        <meta name="author" content="forresst" />
        <script src="../scripts_js/fonctions.js"></script>
        <script type="text/javascript" src="../scripts_js/XMLHttpRequest.js"></script>
        <script src="../scripts_js/jquery-1.10.0.min.js"></script>
        <script src="../scripts_js/jquery.mobile-1.3.0.js"></script>
        <script src="../scripts_js/jquery-ui.js"></script>
        <script src="../scripts_js/jquery.ui.touch-punch.js"></script>

    </head>
    <body onload="initActivite()">

        <script>
        var pic1 = new Array();
        var pic2 = new Array();
        var idAct;
        var bd;
        var son;
        var ins;
        var nbPicto;
        var width;
        var height = window.innerHeight / 6;

        function initActivite() {
            var xhr = getXMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                    //alert("[" + xhr.responseText + "]");
                    //callback(xhr.responseText);
                    var docXML = xhr.responseText;
                    var listeDesActivites = stringToXML(docXML);
                    remplirinfos(listeDesActivites);
                }
            };
            var fd = new FormData();
            fd.append("identifiant", extractUrlParams('id'));

            xhr.open("POST", "../scripts_php/activite_recuperer_mysql.php", false);
            xhr.send(fd);
        }

        function remplirinfos(xml) {
            var listeDAdultes = xml.getElementsByTagName("activite");
            idAct = listeDAdultes[0].getElementsByTagName("identifiant")[0].childNodes[0].nodeValue;
            bd = listeDAdultes[0].getElementsByTagName("bordures")[0].childNodes[0].nodeValue;
            son = listeDAdultes[0].getElementsByTagName("son")[0].childNodes[0].nodeValue;
            var cons = document.createElement('div');
            cons.setAttribute('style', "width: 100%; text-align: center; position: fixed; margin-top: 3%; font-size: "+ window.innerHeight / 20 + "px; ");
            cons.appendChild(document.createTextNode(listeDAdultes[0].getElementsByTagName("instruction")[0].childNodes[0].nodeValue));
            document.getElementsByTagName('body')[0].appendChild(cons);
            ins = listeDAdultes[0].getElementsByTagName("instruction")[0].childNodes[0].nodeValue;
            initPictos();

        }

        function initPictos() {
            var xhr = getXMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                    //alert("[" + xhr.responseText + "]");
                    //callback(xhr.responseText);
                    var docXML = xhr.responseText;
                    var listeDesActivites = stringToXML(docXML);
                    remplirinfos2(listeDesActivites);
                }
            };
            var fd = new FormData();
            fd.append("identifiant", extractUrlParams('id'));

            xhr.open("POST", "../scripts_php/deplaceLayout_recuperer_mysql.php", false);
            xhr.send(fd);
        }
        function remplirinfos2(xml) {
            var listeDAdultes = xml.getElementsByTagName("activite");
            nbPicto = listeDAdultes[0].getElementsByTagName("nombre")[0].childNodes[0].nodeValue;
             width = window.innerWidth / (nbPicto * 2);
            init();

        }

        function infosPictos() {
            //alert(width+" "+window.innerWidth+" "+nbPicto);
            var xhr = getXMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                    //alert("[" + xhr.responseText + "]");
                    //callback(xhr.responseText);
                    var docXML = xhr.responseText;
                    var listeDesActivites = stringToXML(docXML);
                    placerRectangle(listeDesActivites);
                }
            };
            var fd = new FormData();
            fd.append("identifiant", idAct);

            xhr.open("POST", "../scripts_php/activite_has_Pictogramme_recuperer_par_activite.php", false);
            xhr.send(fd);
        }

        function findPicto(id, num, emp) {
            var xhr = getXMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                    //alert("[" + xhr.responseText + "]");
                    //callback(xhr.responseText);
                    var docXML = xhr.responseText;
                    var listeDesActivites = stringToXML(docXML);
                    ajouterPicto(listeDesActivites, id, num, emp);
                }
            };
            var fd = new FormData();
            fd.append("identifiant", id);

            xhr.open('POST', "../scripts_php/picto_recuperer_mysql.php", false);
            xhr.send(fd);
        }


       

        function placerRectangle(xml) {
            var pla = new Array();
            var tagnom = xml.getElementsByTagName('listeDesActivites');
            var img = tagnom[0].getElementsByTagName('activite');
            for (var i = 0; i < nbPicto; i++) {
                pla[i] = (i + 1);
            }
            pla.shuffle();     // on mélange le tableau
            
            
            for (var i = 0; i < img.length; i++) {
                //alert(img[i].getElementsByTagName('identifiant')[0].firstChild.nodeValue);
                var id = img[i].getElementsByTagName('pictogramme')[0].firstChild.nodeValue;
                var num = img[i].getElementsByTagName('numero')[0].firstChild.nodeValue;
                //alert(pla[i]);
                //var emp = img[i].getElementsByTagName('emplacement')[0].firstChild.nodeValue;
                findPicto(id, pla[i], num);
            }

            
          
        }
        
        function ajouterPicto(xml,id, num, emp ){
             var listeDAdultes = xml.getElementsByTagName("pictogramme");

            var ul = document.getElementById(num+'_1');
            //alert(ul.id);
            var tdli = document.createElement('li');

                tdli.setAttribute('id', emp);
                //tdli.setAttribute('onclick', "alert(\"cc\")");
                var tdNom = tdli.appendChild(document.createElement("img"));
                tdNom.setAttribute('src', "../imagesPicto/" + listeDAdultes[0].getElementsByTagName('image')[0].firstChild.nodeValue);
                tdNom.setAttribute('width', (width / 2));
                tdNom.setAttribute('height', (height / 2));
                ul.appendChild(tdli);
                $(function() {
                    $("#"+emp).mouseenter(function() {
                     var audioElement2 = document.createElement('audio');
                    audioElement2.setAttribute('src', "../sonPicto/" + listeDAdultes[0].getElementsByTagName('son')[0].firstChild.nodeValue);
                    audioElement2.play();
                   });

                });
        }

        function init() {
            
            //Image de fond
            var html = document.getElementsByTagName('html')[0];
            if (bd === '2') {
                html.setAttribute('style', "height: 100%; min-height: 100%; background-image: url(../images/deux_bordures.png); background-position:center; background-repeat:no-repeat; background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%; -moz-background-size: 100% 100%;");

            }
            else {
                if (bd === '4') {
                    html.setAttribute('style', "height: 100%; min-height: 100%; background-image: url(../images/quatre_bordures.png); background-position:center; background-repeat:no-repeat; background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%; -moz-background-size: 100% 100%;");
                }

            }

           

            var body = document.getElementsByTagName('body')[0];
            // Ajout des carrés pour déposer les pictogrames
  
            var marge = 50;
            for (var i = 0; i < nbPicto; i++) {
                var div = document.createElement('div');
                div.setAttribute('style', "display: inline-block; margin-left: " + marge + "px; margin-top: 12%; border: 5px black solid; width: " + width + "px; height: " + height + "px; position: fixed;");
                var ul = document.createElement('ul');
                ul.setAttribute('id', (i+1) + "_1");
                ul.setAttribute('class', "connectedSortable");
                ul.setAttribute('style', "display: inline-block; list-style-type : none ;width: " + width + "px; height: " + height + "px; margin: 0px;  padding-left: " + (width / 4) + "px; padding-top: " + (height / 4) + "px; border: 0px");

                marge += (width * 2);
                div.appendChild(ul);
                body.appendChild(div);
                $(function() {
                    $("#" + ul.id).sortable({
                        connectWith: ".connectedSortable",
                        revert: true
                        
                    }).disableSelection()

                });
            }
            
            var marge = 50;
            for (var i = 0; i < nbPicto; i++) {
                var div = document.createElement('div');
                div.setAttribute('style', "display: inline-block; margin-top: " + window.innerHeight / 1.5 + "px; margin-left: " + marge + "px;border: 5px red solid; width: " + width + "px; height: " + height + "px; position: fixed;");
                var ul = document.createElement('ul');
                ul.setAttribute('id', (parseInt(i)+1)+"_2");
                ul.setAttribute('class', "connectedSortable");
                ul.setAttribute('style', "display: inline-block; list-style-type : none ;width: " + width + "px; height: " + height + "px; margin: 0px;  padding-left: " + (width / 4) + "px; padding-top: " + (height / 4) + "px; border: 0px");

                marge += (width * 2);
                div.appendChild(ul);
                body.appendChild(div);
                $(function() {
                    $("#" + ul.id).sortable({
                        connectWith: ".connectedSortable",
                        revert: true,
                        receive: function(event, ui) {
                            var ul = this.id;
                            var li = ui.item.closest('ul').children().attr("id")+"_2";
                            if (ul !== li ) {
                                $(ui.sender).sortable("cancel");
                            }
                            else {
                                isFinished();
                            }
                        }

                    }).disableSelection();

                });
            }
            infosPictos();
        }
        
        function isFinished(){
             var isempty = 0;
            var ul = document.getElementsByTagName('ul');
                for (var i = 0; i < ul.length; i++) {
                    if (ul[i].id.indexOf("_2") !== -1) {
                        var li = ul[i].getElementsByTagName('li');
                        if (typeof(li[0]) !== "undefined") {
                            isempty = 1;
                        }
                        else {
                            isempty = 0;
                            break;
                        }

                    }
                }
                if(isempty === 1){
                    var audioElement2 = document.createElement('audio');
                    audioElement2.setAttribute('src', "../sonsActivite/" + son);
                    audioElement2.setAttribute('onended', "redirection()");
                    audioElement2.play();
                    alert('Bravo vous avez fini l\'exercice');
                }

        }
       
       function redirection() {
           window.location = "../partie_lecteur/index.html";
       }
       
        

        function extractUrlParams(nom) {
            var t = location.search.substring(1).split('&');
            for (var i = 0; i < t.length; i++) {
                var x = t[ i ].split('=');
                if (x[0] == nom) {
                    return x[1];
                }
            }
            return null;
        }

        function randomInt(mini, maxi)
        {
            var nb = mini + (maxi + 1 - mini) * Math.random();
            return Math.floor(nb);
        }

        Array.prototype.shuffle = function(n)
        {
            if (!n)
                n = this.length;
            if (n > 1)
            {
                var i = randomInt(0, n - 1);
                var tmp = this[i];
                this[i] = this[n - 1];
                this[n - 1] = tmp;
                this.shuffle(n - 1);
            }
        }
        

        
        </script>
    </body>
</html>